<?php
$cs = Yii::app()->clientScript;

$cs->registerCoreScript('jquery.ui');
$cs->registerCoreScript('bbq');
$cs->registerCoreScript('cookie');
$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/jquery.ui.nestedSortable.js');
$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/jquery.placeholder.min.js');
$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/json2.js');

$this->breadcrumbs=array(
    'Pages'=>array('index'),
    'Manage',
);

$this->menu=array(
    array('label'=>'Create Page', 'url'=>array('create')),
    array('label'=>'Activate selected pages', 'url'=>array('/Core/service/ajax', 'SID'=>'Cms.page.changeStatus', 'value'=>1), 'linkOptions'=>array('class'=>'change-status')),
    array('label'=>'Deactivate selected pages', 'url'=>array('/Core/service/ajax', 'SID'=>'Cms.page.changeStatus', 'value'=>0), 'linkOptions'=>array('class'=>'change-status')),
    array('label'=>'Copy selected pages', 'url'=>'#', 'linkOptions'=>array('class'=>'copy-pages')),
    array('label'=>'Create Flash Content Page', 'url'=>array('create', 'page_type'=>'flash_content')),
);

$script = "
jQuery.initNestedSortable = function()
{
    var timer = null;
    jQuery('#list-container').nestedSortable({
        disableNesting: 'no-nest',
        forcePlaceholderSize: true,
        handle: '.sort-handle',
        items: '.sortable',
        opacity: .6,
        placeholder: 'placeholder',
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: '> table',
        'listType' : 'ul',
        update: function(event, ui){
            jQuery('#list-container').nestedSortable('disable');
            var serialized = jQuery('#list-container').nestedSortable('serialize');
            jQuery('.ordering-updated').remove();
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            jQuery.get('".$this->createUrl('/Core/service/ajax', array('SID'=>'Cms.page.reorder'))."', serialized, function(res){
                jQuery('#list-container').nestedSortable('enable');
                res = eval(res);
                if (res.errors != undefined && res.errors.length <= 0) {
                    var message = jQuery('<div></div');
                    message.addClass('ordering-updated')
                        .text('The display order of your categories has been updated successfully.');
                    jQuery('.grid-view').before(message);
                    timer = setTimeout(function(){jQuery('.ordering-updated').remove()}, 5000);
                } else {
                    var message = 'Error';
                    if (jQuery.isArray(res.errors.ErrorCode))
                        message = res.errors.ErrorCode.join('. ');
                    alert(message);
                }
            });
        }
    });
};
jQuery.initNestedSortable();
";
$cs->registerScript(__CLASS__.'#InitNestedSortable', $script);
$script = "
jQuery('.status-column a').live('click', function(){
    var _this = jQuery(this);
    var href = jQuery(this).attr('href');
    jQuery.get(href, function(res){
        res = eval(res);
        if (res.errors != undefined && res.errors.length <= 0) {
            //update class, value
            var params = jQuery.deparam.querystring(href);
            params.value = parseInt(params.value) == 1 ? 0 : 1;
            href = jQuery.param.querystring(href, {value : params.value});
            _this.attr('href', href);
            if (params.value == 0)
                _this.addClass('active');
            else
                _this.removeClass('active');
        } else {
            var message = 'Error';
            if (jQuery.isArray(res.errors.ErrorCode))
                message = res.errors.ErrorCode.join('. ');
            alert(message);
        }
    });
    return false;
});

jQuery('.crud-menu .change-status').live('click',function() {
    var data = [];
    jQuery.each(jQuery('input.select-on-check'), function(){
        if (jQuery(this).attr('checked'))
            data.push(jQuery(this).val());
    });
    if (data.length <= 0)
    {
        alert('No item selected.');
        return false;
    }
    
    var href = jQuery(this).attr('href');
    jQuery.get(href, {'ids' : data}, function(res){
        res = eval(res);
        if (res.errors != undefined && res.errors.length <= 0) {
            jQuery('.grid-view').load('".$this->createUrl('/Cms/admin/page/admin')." .grid-view > *', function(){
                jQuery.initNestedSortable();
            });
        } else {
            var message = 'Error';
            if (jQuery.isArray(res.errors.ErrorCode))
                message = res.errors.ErrorCode.join('. ');
            alert(message);
        }
    });
    return false;
});

function get_link_delete(url, data)
{
    var valid = true;
    var delete_data = 0;
    if (confirm('Do you want to delete the page content also ?\\nContent used by other pages will not be delete. You will be able to confirm your deletion on the next step.'))
    {
        delete_data = 1;
        if (!confirm('Are you sure to delete the page and its content ?'))
            valid = false;
    }
    else
        if (!confirm('Are you sure to delete the page ? Page content will not be deleted.'))
            valid = false;
    
    data = jQuery.extend({'delete_data' : delete_data}, data);
    return {
        url : jQuery.param.querystring(url, data),
        valid : valid
    };
}

jQuery('.actions-column a.delete').live('click', function(){
    var _this = jQuery(this);
    
    var url = jQuery(this).attr('href');
    var data = get_link_delete(url, {});
    if (data.valid == false)
        return false;
    
    jQuery.post(data.url, function(res){
        jQuery('.grid-view').load('".$this->createUrl('/Cms/admin/page/admin')." .grid-view > *', function(){
            jQuery.initNestedSortable();
        });
    });
    return false;
});
jQuery('.check-all').live('click', function(){
    jQuery('.checkbox-column input').attr('checked', jQuery(this).attr('checked'));
});
jQuery('.checkbox-column input').live('click', function(){
    if (!jQuery(this).attr('checked'))
        jQuery('.check-all').attr('checked', false);
});
jQuery('.delete-multi').live('click', function(){
    var data = [];
    jQuery.each(jQuery('.checkbox-column input:checked'), function(){
        data.push(jQuery(this).val());
    });
    if (data.length <= 0) {
        alert('Please select at least one category');
        return false;
    }
    
    var url = '".$this->createUrl('delete')."';
    data = get_link_delete(url, {'ids' : data});
    if (data.valid == false)
        return false;
    
    jQuery.post(data.url, function(res){
        jQuery('.grid-view').load('".$this->createUrl('/Cms/admin/page/admin')." .grid-view > *', function(){
            jQuery.initNestedSortable();
        });
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#Actions', $script);

$script = "
jQuery.expr[':'].contains = function(a, i, m) { 
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
};
jQuery('.filters input').change(function(){
    //remove all old selected row
    jQuery('#list-container .items tr.selected').removeClass('selected');
    var inputTitle = jQuery('.filters #title');
    var inputUrl = jQuery('.filters #url');
    var title = inputTitle.val();
    var url = inputUrl.val();
    var titles = [];
    if (title.length)
    {
        jQuery.each(jQuery('#list-container .items tr').find(\"td:eq(1):contains('\"+title+\"')\"), function(){
            titles.push(jQuery(this).parent());
        });
        if (inputTitle.next().hasClass('clear') == false)
        {
            inputTitle.after(jQuery('<span></span>').addClass('clear'));
        }
    }
    else
        inputTitle.next('.clear').remove();
    var urls = []
    if (url.length)
    {
        jQuery.each(jQuery('#list-container .items tr').find(\"td:eq(2):contains('\"+url+\"')\"), function(){
            urls.push(jQuery(this).parent());
        });
        if (inputUrl.next().hasClass('clear') == false)
        {
            inputUrl.after(jQuery('<span></span>').addClass('clear'));
        }
    }
    else
        inputUrl.next('.clear').remove();
    //hightlight matches
    if (title.length && url.length)
    {
        jQuery.each(titles, function(index, title){
            jQuery.each(urls, function(index, url){
                if (title.get(0) == url.get(0))
                {
                    if (jQuery(this).hasClass('selected') == false)
                        jQuery(this).addClass('selected');
                }
            })
        });
    }
    else
    {
        jQuery.each(titles, function(){
            if (jQuery(this).hasClass('selected') == false)
                jQuery(this).addClass('selected');
        });
        jQuery.each(urls, function(){
            if (jQuery(this).hasClass('selected') == false)
                jQuery(this).addClass('selected');
        });
    }
});
jQuery('.filters').delegate('.clear', 'click', function(){
    jQuery(this).prev('input').val('').trigger('change');
    return false;
});
";
$cs->registerScript(__CLASS__.'#Filters', $script);

$script = "
jQuery('.filters input').placeholder();
";
$cs->registerScript(__CLASS__.'#Placeholder', $script);

$script = "
jQuery('#compare_workflow').change(function(){
    var target_id = jQuery(this).val();
    var url = '".$this->createUrl('/Cms/admin/page/compare')."';
    url = jQuery.param.querystring(url, {'target_id' : target_id});
    window.location = decodeURIComponent(url);
});
";
$cs->registerScript(__CLASS__.'#CompareWith', $script);

$script = "
var toggle = jQuery.cookie('toggle') || {};
if (typeof toggle === 'string')
{
    var tmp = {};
    JSON.parse(toggle, function(key,value){
        tmp[key] = value;
        key = key.replace('_','-');
        if (value == 0)
        {
            $('#'+key+' > .items .collapse').addClass('expand');
            $('#'+key+' > ul').hide();
        }
    });
    toggle = tmp;
}
jQuery('.sort-handle .expand, .sort-handle .collapse').click(function(){
    var id = jQuery(this).closest('.sortable').attr('id').replace('-','_');
    if (jQuery(this).hasClass('expand'))
    {
        jQuery(this).removeClass('expand')
            .closest('.sortable').find('> ul').show();
        toggle[id] = 1;
    }
    else
    {
        jQuery(this).addClass('expand')
            .closest('.sortable').find('> ul').hide();
        toggle[id] = 0;
    }
    jQuery.cookie('toggle', JSON.stringify(toggle));
    return false;
});
";
$cs->registerScript(__CLASS__.'#Toggle', $script);
?>

<h2>Manage Pages</h2>
<style type="text/css">
.grid-view ul {padding: 0; display: block; margin: 0;}
.grid-view ul li {list-style: none;}
.grid-view .sort-handle {cursor: move;}
.grid-view table.items {border-bottom: 1px solid #FFFFFF;}
#list-container ul {padding-left: 20px;}
.ordering-updated {background: url(<?php echo Yii::app()->theme->baseUrl;?>/images/notifications.gif) 10px center #EEEEEE no-repeat; padding: 5px 0 5px 30px; margin: 10px 0;}
.placeholder {background: #DBDBDB; border-bottom: 1px solid #FFFFFF;}
.filters span {padding: 5px 10px; background: url(<?php echo Yii::app()->theme->baseUrl;?>/images/clear-filter.png) no-repeat left center; cursor: pointer;}
.grid-view table.items th, .grid-view table.items td { border: 1px solid white;}
.grid-view table.items th { border-bottom: 1px solid #DDDDDD; }
.grid-view .status-column {width: 38px;}
.view-mode select {display: none;}
</style>

<div class="filters">
    Search By: <?php echo CHtml::textField('title', '', array('placeholder'=>'Page Title'));?> <?php echo CHtml::textField('url', '', array('placeholder'=>'Default Url'));?>
</div>
<div class="view-mode" style="margin-top: -20px; margin-bottom: 5px;">    
    <?php echo CHtml::link('Grid View', array('adminFlat'), array('class'=>'grid', 'title'=>'Grid View'));?>
    <?php echo CHtml::dropDownList('compare_workflow', '', $workflows, array('style'=>'float:right;', 'prompt'=>'---Compare with---'));?>
</div>
<div class="grid-view">
    <table class="items">
        <thead>
            <tr>
                <th align="center" width="20"><?php echo CHtml::checkBox('check_all', false, array('class'=>'check-all'));?></th>
                <th align="left">Title</th>
                <th width="200">Notes</th>
                <th width="200">Default Url</th>
                <th width="35">Live</th>
                <th width="70">Sitemap</th>
                <th width="35">Status</th>
                <th width="100">&nbsp;</th>
            </tr>
        </thead>
    </table>
<?php if (count($models)):?>
    <ul id="list-container">
        <?php $this->renderAdminNestedPage(dirname(__FILE__).DIRECTORY_SEPARATOR.'_admin_item.php', $models);?>
    </ul>
    <?php
    $this->menu[] = array('label' => 'Delete selected items', 'url'=>$this->createUrl('delete'), 'linkOptions' => array('class'=>'delete-multi'));
    ?>
<?php else:?>
    <table class="items">
        <tr class="odd">
            <td colspan="4"><?php echo Yii::t('zii','No results found.');?></td>
        </tr>
    </table>
<?php endif;?>
</div>
<?php $this->renderPartial('_form_copy', array('sites'=>$sites));?>
<?php $this->renderPartial('_form_duplicate');?>
<?php
$script = "
jQuery.edit_log_link = '';
jQuery('.edit-log').live('click', function(){
    jQuery.edit_log_link = jQuery(this);
    jQuery('#edit-log textarea').val(jQuery(this).prev('span').text());
    jQuery.fancybox({
        'type' : 'inline',
        'href' : '#edit-log',
        'autoScale'     : false,
        'titleShow'     : false,
        'hideOnOverlayClick'     : false,
        'width'         : 398,
        'model'         : true
    });
    return false;
});

jQuery('#edit-log .save-log').live('click', function(){
    jQuery.fancybox.close();
    var data = jQuery('#edit-log textarea').val();
    jQuery.post(jQuery.edit_log_link.attr('href'), {data : data}, function(){
        jQuery.edit_log_link.prev('span').text(data);
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#EditLog', $script);
?>
<div style="display: none;">
    <div id="edit-log" style="width: 398px;">
        <div><?php echo CHtml::textArea('log', '', array('cols'=>70, 'rows'=>7, 'style'=>'width:388px;'));?></div>
        <div align="right">
            <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
            <?php echo CHtml::button('Save', array('class'=>'save-log'));?>
        </div>
    </div>
</div>